package com.leetcode.根据数据结构分类.二叉树;

import com.leetcode.datastructure.TreeNode;

import java.util.*;

/**
 * @author: xiaomi
 * @date: 2020/12/24
 * @description:    剑指 Offer 32 - I. 从上到下打印二叉树
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
 */
public class A_剑指Offer32_I_从上到下打印二叉树 {

    /**
     * 说白了就是层序遍历
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        List<Integer> res= new ArrayList<>();
        if (root==null){
            //需要返回一个空数组
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur=root;
        queue.offer(cur);

        while (!queue.isEmpty()){
            cur=queue.poll();
            res.add(cur.val);
            if (cur.left!=null){
                queue.offer(cur.left);
            }
            if (cur.right!=null){
                queue.offer(cur.right);
            }
        }
        ///TODO:对于 list 转 int[]：由于只能直接转 Object[]，如果要转 int[] 那就只能老老实实遍历
        int[] result = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            result[i]=res.get(i);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
